<div class="content">
        <h1 class="page-title">Java 8 Concurrency Tutorial: Synchronization and Locks</h1>

<p class="page-subtitle" data-page-url="http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/">
    <span class="post-date">April 30, 2015</span><br>
    <span class="share-count-total"></span>
</p>

<div id="carbonads-container">
    <script async="" type="text/javascript" src="//cdn.carbonads.com/carbon.js?zoneid=1673&amp;serve=C6AILKT&amp;placement=winterbecom" id="_carbonads_js"></script>
</div>

<div class="post">
    <p>Welcome to the second part of my Java 8 Concurrency Tutorial out of a series of guides teaching multi-threaded programming in Java 8 with easily understood code examples. In the next 15 min you learn how to synchronize access to mutable shared variables via the synchronized keyword, locks and semaphores.</p>

<ul>
<li>Part 1: <a href="/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/">Threads and Executors</a></li>
<li>Part 2: Synchronization and Locks</li>
<li>Part 3: <a href="/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/">Atomic Variables and ConcurrentMap</a></li>
</ul>

<p>The majority of concepts shown in this article also work in older versions of Java. However the code samples focus on Java 8 and make heavy use of lambda expressions and  new concurrency features. If you're not yet familiar with lambdas I recommend reading my <a href="/posts/2014/03/16/java-8-tutorial/">Java 8 Tutorial</a> first.</p>

<p>For simplicity the code samples of this tutorial make use of the two helper methods <code>sleep(seconds)</code> and <code>stop(executor)</code> as defined <a href="https://github.com/winterbe/java8-tutorial/blob/master/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java">here</a>.</p>

<h3>Synchronized</h3>

<p>In the <a href="(/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/)">previous tutorial</a> we've learned how to execute code in parallel via executor services. When writing such multi-threaded code you have to pay particular attention when accessing shared mutable variables concurrently from multiple threads. Let's just say we want to increment an integer which is accessible simultaneously from multiple threads.</p>

<p>We define a field <code>count</code> with a method <code>increment()</code> to increase count by one:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

<span class="kt">void</span> <span class="nf">increment</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">count</span> <span class="o">=</span> <span class="n">count</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div>
<p>When calling this method concurrently from multiple threads we're in serious trouble:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>

<span class="n">IntStream</span><span class="o">.</span><span class="na">range</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">10000</span><span class="o">)</span>
    <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="k">this</span><span class="o">::</span><span class="n">increment</span><span class="o">));</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>

<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">count</span><span class="o">);</span>  <span class="c1">// 9965</span>
</code></pre></div>
<p>Instead of seeing a constant result count of 10000 the actual result varies with every execution of the above code. The reason is that we share a mutable variable upon different threads without synchronizing the access to this variable which results in a <a href="http://en.wikipedia.org/wiki/Race_condition">race condition</a>.</p>

<p>Three steps have to be performed in order to increment the number: (i) read the current value, (ii) increase this value by one and (iii) write the new value to the variable. If two threads perform these steps in parallel it's possible that both threads perform step 1 simultaneously thus reading the same current value. This results in lost writes so the actual result is lower. In the above sample 35 increments got lost due to concurrent unsynchronized access to count but you may see different results when executing the code by yourself.</p>

<p>Luckily Java supports thread-synchronization since the early days via the <code>synchronized</code> keyword. We can utilize <code>synchronized</code> to fix the above race conditions when incrementing the count:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kd">synchronized</span> <span class="kt">void</span> <span class="nf">incrementSync</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">count</span> <span class="o">=</span> <span class="n">count</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div>
<p>When using <code>incrementSync()</code> concurrently we get the desired result count of 10000. No race conditions occur any longer and the result is stable with every execution of the code:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>

<span class="n">IntStream</span><span class="o">.</span><span class="na">range</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">10000</span><span class="o">)</span>
    <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="k">this</span><span class="o">::</span><span class="n">incrementSync</span><span class="o">));</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>

<span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">count</span><span class="o">);</span>  <span class="c1">// 10000</span>
</code></pre></div>
<p>The <code>synchronized</code> keyword is also available as a block statement.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="kt">void</span> <span class="nf">incrementSync</span><span class="o">()</span> <span class="o">{</span>
    <span class="kd">synchronized</span> <span class="o">(</span><span class="k">this</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">count</span> <span class="o">=</span> <span class="n">count</span> <span class="o">+</span> <span class="mi">1</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p>Internally Java uses a so called <em>monitor</em> also known as <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html">monitor lock or intrinsic lock</a> in order to manage synchronization. This monitor is bound to an object, e.g. when using synchronized methods each method share the same monitor of the corresponding object.</p>

<p>All implicit monitors implement the <em>reentrant</em> characteristics. Reentrant means that locks are bound to the current thread. A thread can safely acquire the same lock multiple times without running into deadlocks (e.g. a synchronized method calls another synchronized method on the same object).</p>

<h3>Locks</h3>

<p>Instead of using implicit locking via the <code>synchronized</code> keyword the Concurrency API supports various explicit locks specified by the <code>Lock</code> interface. Locks support various methods for finer grained lock control thus are more expressive than implicit monitors.</p>

<p>Multiple lock implementations are available in the standard JDK which will be demonstrated in the following sections.</p>

<h4>ReentrantLock</h4>

<p>The class <code>ReentrantLock</code> is a mutual exclusion lock with the same basic behavior as the implicit monitors accessed via the <code>synchronized</code> keyword but with extended capabilities. As the name suggests this lock implements reentrant characteristics just as implicit monitors.</p>

<p>Let's see how the above sample looks like using <code>ReentrantLock</code>:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ReentrantLock</span> <span class="n">lock</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">ReentrantLock</span><span class="o">();</span>
<span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>

<span class="kt">void</span> <span class="nf">increment</span><span class="o">()</span> <span class="o">{</span>
    <span class="n">lock</span><span class="o">.</span><span class="na">lock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">count</span><span class="o">++;</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlock</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div>
<p>A lock is acquired via <code>lock()</code> and released via <code>unlock()</code>. It's important to wrap your code into a <code>try/finally</code> block to ensure unlocking in case of exceptions. This method is thread-safe just like the synchronized counterpart. If another thread has already acquired the lock subsequent calls to <code>lock()</code> pause the current thread until the lock has been unlocked. Only one thread can hold the lock at any given time.</p>

<p>Locks support various methods for fine grained control as seen in the next sample:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
<span class="n">ReentrantLock</span> <span class="n">lock</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">ReentrantLock</span><span class="o">();</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="n">lock</span><span class="o">.</span><span class="na">lock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">1</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlock</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">});</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Locked: "</span> <span class="o">+</span> <span class="n">lock</span><span class="o">.</span><span class="na">isLocked</span><span class="o">());</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Held by me: "</span> <span class="o">+</span> <span class="n">lock</span><span class="o">.</span><span class="na">isHeldByCurrentThread</span><span class="o">());</span>
    <span class="kt">boolean</span> <span class="n">locked</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">tryLock</span><span class="o">();</span>
    <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Lock acquired: "</span> <span class="o">+</span> <span class="n">locked</span><span class="o">);</span>
<span class="o">});</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>
</code></pre></div>
<p>While the first task holds the lock for one second the second task obtains different information about the current state of the lock:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">Locked: true
Held by me: false
Lock acquired: false
</code></pre></div>
<p>The method <code>tryLock()</code> as an alternative to <code>lock()</code> tries to acquire the lock without pausing the current thread. The boolean result must be used to check if the lock has actually been acquired before accessing any shared mutable variables.</p>

<h4>ReadWriteLock</h4>

<p>The interface <code>ReadWriteLock</code> specifies another type of lock maintaining a pair of locks for read and write access. The idea behind read-write locks is that it's usually safe to read mutable variables concurrently as long as nobody is writing to this variable. So the read-lock can be held simultaneously by multiple threads as long as no threads hold the write-lock. This can improve performance and throughput in case that reads are more frequent than writes.</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
<span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
<span class="n">ReadWriteLock</span> <span class="n">lock</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">ReentrantReadWriteLock</span><span class="o">();</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="n">lock</span><span class="o">.</span><span class="na">writeLock</span><span class="o">().</span><span class="na">lock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">1</span><span class="o">);</span>
        <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"foo"</span><span class="o">,</span> <span class="s">"bar"</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">writeLock</span><span class="o">().</span><span class="na">unlock</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">});</span>
</code></pre></div>
<p>The above example first acquires a write-lock in order to put a new value to the map after sleeping for one second. Before this task has finished two other tasks are being submitted trying to read the entry from the map and sleep for one second:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">Runnable</span> <span class="n">readTask</span> <span class="o">=</span> <span class="o">()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="n">lock</span><span class="o">.</span><span class="na">readLock</span><span class="o">().</span><span class="na">lock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">"foo"</span><span class="o">));</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">1</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">readLock</span><span class="o">().</span><span class="na">unlock</span><span class="o">();</span>
    <span class="o">}</span>
<span class="o">};</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="n">readTask</span><span class="o">);</span>
<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="n">readTask</span><span class="o">);</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>
</code></pre></div>
<p>When you execute this code sample you'll notice that both read tasks have to wait the whole second until the write task has finished. After the write lock has been released both read tasks are executed in parallel and print the result simultaneously to the console. They don't have to wait for each other to finish because read-locks can safely be acquired concurrently as long as no write-lock is held by another thread.</p>

<h4>StampedLock</h4>

<p>Java 8 ships with a new kind of lock called <code>StampedLock</code> which also support read and write locks just like in the example above. In contrast to <code>ReadWriteLock</code> the locking methods of a <code>StampedLock</code> return a stamp represented by a <code>long</code> value. You can use these stamps to either release a lock or to check if the lock is still valid. Additionally stamped locks support another lock mode called <em>optimistic locking</em>.</p>

<p>Let's rewrite the last example code to use <code>StampedLock</code> instead of <code>ReadWriteLock</code>:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
<span class="n">Map</span><span class="o">&lt;</span><span class="n">String</span><span class="o">,</span> <span class="n">String</span><span class="o">&gt;</span> <span class="n">map</span> <span class="o">=</span> <span class="k">new</span> <span class="n">HashMap</span><span class="o">&lt;&gt;();</span>
<span class="n">StampedLock</span> <span class="n">lock</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">StampedLock</span><span class="o">();</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">writeLock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">1</span><span class="o">);</span>
        <span class="n">map</span><span class="o">.</span><span class="na">put</span><span class="o">(</span><span class="s">"foo"</span><span class="o">,</span> <span class="s">"bar"</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlockWrite</span><span class="o">(</span><span class="n">stamp</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">});</span>

<span class="n">Runnable</span> <span class="n">readTask</span> <span class="o">=</span> <span class="o">()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">readLock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">map</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="s">"foo"</span><span class="o">));</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">1</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlockRead</span><span class="o">(</span><span class="n">stamp</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">};</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="n">readTask</span><span class="o">);</span>
<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="n">readTask</span><span class="o">);</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>
</code></pre></div>
<p>Obtaining a read or write lock via <code>readLock()</code> or <code>writeLock()</code> returns a stamp which is later used for unlocking within the finally block. Keep in mind that stamped locks don't implement reentrant characteristics. Each call to lock returns a new stamp and blocks if no lock is available even if the same thread already holds a lock. So you have to pay particular attention not to run into deadlocks.</p>

<p>Just like in the previous <code>ReadWriteLock</code> example both read tasks have to wait until the write lock has been released. Then both read tasks print to the console simultaneously because multiple reads doesn't block each other as long as no write-lock is held.</p>

<p>The next example demonstrates <em>optimistic locking</em>:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
<span class="n">StampedLock</span> <span class="n">lock</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">StampedLock</span><span class="o">();</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">tryOptimisticRead</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Optimistic Lock Valid: "</span> <span class="o">+</span> <span class="n">lock</span><span class="o">.</span><span class="na">validate</span><span class="o">(</span><span class="n">stamp</span><span class="o">));</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">1</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Optimistic Lock Valid: "</span> <span class="o">+</span> <span class="n">lock</span><span class="o">.</span><span class="na">validate</span><span class="o">(</span><span class="n">stamp</span><span class="o">));</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Optimistic Lock Valid: "</span> <span class="o">+</span> <span class="n">lock</span><span class="o">.</span><span class="na">validate</span><span class="o">(</span><span class="n">stamp</span><span class="o">));</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlock</span><span class="o">(</span><span class="n">stamp</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">});</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">writeLock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Write Lock acquired"</span><span class="o">);</span>
        <span class="n">sleep</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlock</span><span class="o">(</span><span class="n">stamp</span><span class="o">);</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Write done"</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">});</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>
</code></pre></div>
<p>An optimistic read lock is acquired by calling <code>tryOptimisticRead()</code> which always returns a stamp without blocking the current thread, no matter if the lock is actually available. If there's already a write lock active the returned stamp equals zero. You can always check if a stamp is valid by calling <code>lock.validate(stamp)</code>.</p>

<p>Executing the above code results in the following output:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">Optimistic Lock Valid: true
Write Lock acquired
Optimistic Lock Valid: false
Write done
Optimistic Lock Valid: false
</code></pre></div>
<p>The optimistic lock is valid right after acquiring the lock. In contrast to normal read locks an optimistic lock doesn't prevent other threads to obtain a write lock instantaneously. After sending the first thread to sleep for one second the second thread obtains a write lock without waiting for the optimistic read lock to be released. From this point the optimistic read lock is no longer valid. Even when the write lock is released the optimistic read locks stays invalid.</p>

<p>So when working with optimistic locks you have to validate the lock every time <em>after</em> accessing any shared mutable variable to make sure the read was still valid.</p>

<p>Sometimes it's useful to convert a read lock into a write lock without unlocking and locking again. <code>StampedLock</code> provides the method <code>tryConvertToWriteLock()</code> for that purpose as seen in the next sample:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">2</span><span class="o">);</span>
<span class="n">StampedLock</span> <span class="n">lock</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">StampedLock</span><span class="o">();</span>

<span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">long</span> <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">readLock</span><span class="o">();</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">count</span> <span class="o">==</span> <span class="mi">0</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">tryConvertToWriteLock</span><span class="o">(</span><span class="n">stamp</span><span class="o">);</span>
            <span class="k">if</span> <span class="o">(</span><span class="n">stamp</span> <span class="o">==</span> <span class="mi">0L</span><span class="o">)</span> <span class="o">{</span>
                <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Could not convert to write lock"</span><span class="o">);</span>
                <span class="n">stamp</span> <span class="o">=</span> <span class="n">lock</span><span class="o">.</span><span class="na">writeLock</span><span class="o">();</span>
            <span class="o">}</span>
            <span class="n">count</span> <span class="o">=</span> <span class="mi">23</span><span class="o">;</span>
        <span class="o">}</span>
        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">count</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="n">lock</span><span class="o">.</span><span class="na">unlock</span><span class="o">(</span><span class="n">stamp</span><span class="o">);</span>
    <span class="o">}</span>
<span class="o">});</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>
</code></pre></div>
<p>The task first obtains a read lock and prints the current value of field <code>count</code> to the console. But if the current value is zero we want to assign a new value of <code>23</code>. We first have to convert the read lock into a write lock to not break potential concurrent access by other threads. Calling <code>tryConvertToWriteLock()</code> doesn't block but may return a zero stamp indicating that no write lock is currently available. In that case we call <code>writeLock()</code> to block the current thread until a write lock is available.</p>

<h3>Semaphores</h3>

<p>In addition to locks the Concurrency API also supports counting semaphores. Whereas locks usually grant exclusive access to variables or resources, a semaphore is capable of maintaining whole sets of permits. This is useful in different scenarios where you have to limit the amount concurrent access to certain parts of your application.</p>

<p>Here's an example how to limit access to a long running task simulated by <code>sleep(5)</code>:</p>
<div class="highlight"><pre><code class="language-java" data-lang="java"><span class="n">ExecutorService</span> <span class="n">executor</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newFixedThreadPool</span><span class="o">(</span><span class="mi">10</span><span class="o">);</span>

<span class="n">Semaphore</span> <span class="n">semaphore</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">Semaphore</span><span class="o">(</span><span class="mi">5</span><span class="o">);</span>

<span class="n">Runnable</span> <span class="n">longRunningTask</span> <span class="o">=</span> <span class="o">()</span> <span class="o">-&gt;</span> <span class="o">{</span>
    <span class="kt">boolean</span> <span class="n">permit</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span>
    <span class="k">try</span> <span class="o">{</span>
        <span class="n">permit</span> <span class="o">=</span> <span class="n">semaphore</span><span class="o">.</span><span class="na">tryAcquire</span><span class="o">(</span><span class="mi">1</span><span class="o">,</span> <span class="n">TimeUnit</span><span class="o">.</span><span class="na">SECONDS</span><span class="o">);</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">permit</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Semaphore acquired"</span><span class="o">);</span>
            <span class="n">sleep</span><span class="o">(</span><span class="mi">5</span><span class="o">);</span>
        <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
            <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">"Could not acquire semaphore"</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">InterruptedException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">IllegalStateException</span><span class="o">(</span><span class="n">e</span><span class="o">);</span>
    <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
        <span class="k">if</span> <span class="o">(</span><span class="n">permit</span><span class="o">)</span> <span class="o">{</span>
            <span class="n">semaphore</span><span class="o">.</span><span class="na">release</span><span class="o">();</span>
        <span class="o">}</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="n">IntStream</span><span class="o">.</span><span class="na">range</span><span class="o">(</span><span class="mi">0</span><span class="o">,</span> <span class="mi">10</span><span class="o">)</span>
    <span class="o">.</span><span class="na">forEach</span><span class="o">(</span><span class="n">i</span> <span class="o">-&gt;</span> <span class="n">executor</span><span class="o">.</span><span class="na">submit</span><span class="o">(</span><span class="n">longRunningTask</span><span class="o">));</span>

<span class="n">stop</span><span class="o">(</span><span class="n">executor</span><span class="o">);</span>
</code></pre></div>
<p>The executor can potentially run 10 tasks concurrently but we use a semaphore of size 5, thus limiting concurrent access to 5. It's important to use a <code>try/finally</code> block to properly release the semaphore even in case of exceptions.</p>

<p>Executing the above code results in the following output:</p>
<div class="highlight"><pre><code class="language-text" data-lang="text">Semaphore acquired
Semaphore acquired
Semaphore acquired
Semaphore acquired
Semaphore acquired
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore
Could not acquire semaphore
</code></pre></div>
<p>The semaphores permits access to the actual long running operation simulated by <code>sleep(5)</code> up to a maximum of 5. Every subsequent call to <code>tryAcquire()</code> elapses the maximum wait timeout of one second, resulting in the appropriate console output that no semaphore could be acquired.</p>

<p>This was the second part out of a series of concurrency tutorials. More parts will be released in the near future, so stay tuned. As usual you find all code samples from this article on <a href="https://github.com/winterbe/java8-tutorial">GitHub</a>, so feel free to fork the repo and try it by your own.</p>

<p>I hope you've enjoyed this article. If you have any further questions send me your feedback in the comments below. You should also <a href="https://twitter.com/winterbe_">follow me on Twitter</a> for more dev-related stuff!</p>

<ul>
<li>Part 1: <a href="/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/">Threads and Executors</a></li>
<li>Part 2: Synchronization and Locks</li>
<li>Part 3: <a href="/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/">Atomic Variables and ConcurrentMap</a></li>
</ul>

</div>

<div class="social-share">
    <a class="github-button" href="https://github.com/winterbe" data-style="mega" aria-label="Follow @winterbe on GitHub">Follow @winterbe</a>
    <script async="" defer="" id="github-bjs" src="https://buttons.github.io/buttons.js"></script>

    <a href="https://twitter.com/winterbe_" class="twitter-follow-button" data-show-count="false" data-size="large" data-dnt="true">Follow @winterbe_</a>
    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>

    <a href="https://twitter.com/share" class="twitter-share-button" {count}="" data-via="winterbe_" data-size="large" data-dnt="true">Tweet</a>
    <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
</div>

<section class="author">
    <div class="avatar"></div>
    Benjamin is Software Engineer, Full Stack Developer at <a href="http://pondus.de/en/homepage/">Pondus</a>, an excited runner and table foosball player.
    Get in touch on <a href="https://twitter.com/winterbe_">Twitter</a>, <a href="https://plus.google.com/105973259367211176218/posts" rel="author">Google+</a> and <a href="https://github.com/winterbe">GitHub</a>.
</section>

<h3 class="center">Read More</h3>

<ul class="tabs center device-large">
    <li class="tab active">
        <a href="#">Recent</a>
    </li>
    <li class="tab">
        <a href="/blog/">All Posts</a>
    </li>
    <li class="tab">
        <a href="/java/">Java</a>
    </li>
    <li class="tab">
        <a href="/javascript/">JavaScript</a>
    </li>
    <li class="tab">
        <a href="/tutorials/">Tutorials</a>
    </li>
</ul>

<ul class="tabs center device-small">
    <li class="tab active">
        <a href="#">Recent</a>
    </li>
    <li class="tab">
        <a href="/blog/">All Posts</a>
    </li>
    <li class="tab">
        <a href="/java/">Java</a>
    </li>
    <li class="tab">
        <a href="/tutorials/">Tutorials</a>
    </li>
</ul>

<ul class="blog-items read-more">
    
    
    <li class="blog-item center">
        <a href="/posts/2015/08/24/integrate-reactjs-into-jquery-webapps/">
            <h1>Integrating React.js into Existing jQuery Web Applications</h1>
        </a>
    </li>
    
    
    
    <li class="blog-item center">
        <a href="/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/">
            <h1>Java 8 Concurrency Tutorial: Atomic Variables and ConcurrentMap</h1>
        </a>
    </li>
    
    
    
    
    
    <li class="blog-item center">
        <a href="/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/">
            <h1>Java 8 Concurrency Tutorial: Threads and Executors</h1>
        </a>
    </li>
    
    
    
    <li class="blog-item center">
        <a href="/posts/2015/03/25/java8-examples-string-number-math-files/">
            <h1>Java 8 API by Example: Strings, Numbers, Math and Files</h1>
        </a>
    </li>
    
    
</ul>

</div>